home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: How to Display a File Backwards?
- Date: 16 Feb 1996 18:33:25 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4g3eplINNo0k@keats.ugrad.cs.ubc.ca>
- References: <4g1rpl$kqo@newsbf02.news.aol.com>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4g1rpl$kqo@newsbf02.news.aol.com>,
- ASCII zero <asciizero@aol.com> wrote:
- >Hello!
- >
- >What is the best way to display a text file backwards, using the standard
- >ANSI C functions, if the file is constantly appended/updated?
-
- This doesn't make that much sense. First of all, ANSI doesn't really specify
- that something _can_ be updating or appending to your file while your program
- is executing, does it?
-
- What do you do if you have already started displaying the file and it gets
- appended to? Your question is pretty vague.
-
- Here is a silly UNIX program that does it with memory maps:
-
-
- #include <sys/types.h>
- #include <sys/mman.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <stdio.h>
- #include <stddef.h>
- #include <errno.h>
-
- int main(argc, argv)
- int argc;
- char **argv;
- {
- int i;
- int fd;
- int size;
- char *where;
-
- if (argc < 2) {
- printf("program to reverse the contents of a file\n");
- printf("usage: %s <file>\n",argv[0]);
- exit(1);
- }
-
- if ((fd = open(argv[1], O_RDWR)) < 0) {
- perror(argv[1]);
- exit(1);
- }
-
-
- /*
- * get size of file
- */
-
- size = lseek(fd, 0, SEEK_END);
-
- /*
- * map file to virtual memory, so "where" points to the beginning
- */
-
- where = (char *) mmap((caddr_t) 0, size, PROT_READ|PROT_WRITE,MAP_FILE|MAP_SHARED, fd, 0);
-
-
- /*
- * if mmap was successful, perform the reversal, else print
- * error message
- */
-
- if (where != (caddr_t) -1)
- for (i = 0; i < size/2; i++) { /* do the reversal :) */
- char tmp = where[i];
- where[i] = where[size-i-1];
- where[size-i-1] = tmp;
- }
- else
- perror("mmap() failed");
-
- munmap(where, size);
- }
-
-
- --
-
-